<template>
  <div style="width: 100%; height: 100%">
    <div :id="className" :style="{ height: height, width: width }" />
  </div>
</template>

<script>
  // name: '单独饼形图'
  import * as echarts from 'echarts'

  export default {
    props: {
      // 过滤器
      className: {
        type: String,
        default: 'chart',
      },
      width: {
        type: String,
        default: '100%',
      },
      height: {
        type: String,
        default: '100%',
      },
      barData: {
        // 数据
        type: Array,
        default: Array,
      },
      pieName: {
        type: String,
        default: '统计',
      },
    },
    data() {
      return {
        chart: null,
      }
    },
    // 监听数据变化
    watch: {
      barData: {
        // 监听数据变化
        deep: true,
        handler(val) {
          this.drawPid(val, this.pieName)
        },
      },
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    mounted() {
      this.$nextTick(function () {
        this.drawPid(this.barData, this.pieName)
      })
    },
    methods: {
      drawPid(postData, name) {
        let legendOption = {}
        let centerSet = ['25%', '53%']
        if (name === '优良等级') {
          centerSet = ['50%', '53%']
          legendOption = {
            top: '10%',
            itemWidth: 13,
            itemHeight: 13,
          }
        } else {
          centerSet = ['25%', '53%']
          legendOption = {
            top: '55%',
            left: '50%',
            orient: 'vertical',
            itemWidth: 13,
            itemHeight: 13,
          }
        }
        const option = {
          title: { text: name },
          tooltip: { trigger: 'item' },
          legend: legendOption,
          series: [
            {
              type: 'pie',
              radius: ['50%', '70%'],
              center: centerSet, // ['25%', '53%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center',
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '15',
                  fontWeight: 'bold',
                },
              },
              labelLine: { show: false },
              data: postData,
            },
          ],
        }
        this.chart = echarts.init(document.getElementById(this.className))
        // 使用刚指定的配置项和数据显示图表。
        this.chart.setOption(option)
      },
    },
  }
</script>
